package com.pactera.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * @program: pactera
 * @description:
 * @author: EC_liqingdian
 * @create: 2020-03-10 14:03
 **/
public class IpUtils {
    private static final Logger log = LoggerFactory.getLogger(IpUtils.class);

    private IpUtils() {
    }

    /**
     * 获取本地IP地址
     *
     * @author: liqingdian
     */
    public static String getLocalIP() throws UnknownHostException {
        if (isWindowsOS()) {
            return InetAddress.getLocalHost().getHostAddress();
        } else {
            return getLinuxLocalIp();
        }
    }

    /**
     * 是否windows
     *
     * @author: liqingdian
     */
    public static boolean isWindowsOS() {
        String osName = System.getProperty("os.name");
        if (StringUtils.isBlank(osName)) {
            return false;
        }
        return osName.toLowerCase().indexOf("windows") > -1;
    }

    /**
     * 获取本地host名称
     *
     * @author: liqingdian
     */
    public static String getLocalHostName() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostName();
    }

    /**
     * 获取Linux下的IP地址
     *
     * @author: liqingdian
     */
    private static String getLinuxLocalIp() {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            log.error(ex.getMessage(), ex);
            ip = "127.0.0.1";
        }
        return ip;
    }
}
